﻿using Account.Api.Client;
using Account.Api.Dtos;
using BootstrapBlazor.Components;
using CyssBlazor.Shared.Infrastructure;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.AccountManager.Roles
{
    public partial class RolePermission
    {

        [CascadingParameter(Name = "BodyContext")]
        private object ObjectModel { set; get; }
        private RoleModel Role
        {
            get
            {
                return (ObjectModel as RoleModel);

            }
        }


        private List<TreeItem> TreeItems { set; get; } = new List<TreeItem>();

        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                var operateResult = await AccountClientFactory.Permission.GetPermissionTrees();
                if (operateResult.IsSuccess == false)
                {
                    await this.Toast("获取权限模板失败" + operateResult.Message);
                }
                else
                {
                    SetTreeItems(operateResult.Data);
                    await InvokeAsync(StateHasChanged);

                    var operateResultRolePermission = await AccountClientFactory.RolePermission.GetRolePermissionByRoleId(Role.Id);
                    if (operateResultRolePermission.IsSuccess == false)
                    {
                        await this.Toast("获取角色权限失败" + operateResultRolePermission.Message);
                    }
                    else
                    {
                        await SetRolePermissionChecked(TreeItems, operateResultRolePermission.Data);
                        await InvokeAsync(StateHasChanged);
                    }

                }

            }
            await base.OnAfterRenderAsync(firstRender);
        }

        private async Task SetRolePermissionChecked(IEnumerable<TreeItem> treeItems, IEnumerable<RolePermissionModel> rolePermissions)
        {
            foreach (var item in treeItems)
            {
                var permissionTree = item.Key as PermissionTreeModel;
                if (permissionTree.IsMenu)
                {

                    if (rolePermissions.Any(x => x.PermissionType == RolePermissionType.Menu && x.MenuId == permissionTree.Menu.Id))
                    {
                        item.Checked = true;
                    }
                }
                else
                {
                    if (rolePermissions.Any(x => x.PermissionType == RolePermissionType.Button && x.PermissionId == permissionTree.Permission.Id))
                    {
                        item.Checked = true;
                    }
                }
                if (item.Items != null && item.Items.Count() > 0)
                {
                    await SetRolePermissionChecked(item.Items, rolePermissions);
                }
            }
        }

        private async Task SaveAsync()
        {
            var SelectPermissions = GetSelectItems(TreeItems);
            var operateResult = await AccountClientFactory.RolePermission.EditRolePermission(SelectPermissions);
            if (operateResult.IsSuccess)
            {
                await this.Alert("修改成功!");
            }
            else
            {
                await this.Alert("修改失败!" + operateResult.Message);
            }
        }

        /// <summary>
        /// 获取所有选中的权限
        /// </summary>
        /// <param name="treeItems"></param>
        /// <returns></returns>
        private IEnumerable<RolePermissionModel> GetSelectItems(IEnumerable<TreeItem> treeItems)
        {
            List<RolePermissionModel> models = new List<RolePermissionModel>();
            foreach (var item in treeItems)
            {
                if (!item.Checked)
                {
                    continue;
                }
                RolePermissionModel model = new RolePermissionModel();
                model.RoleId = Role.Id;

                var permissionTree = item.Key as PermissionTreeModel;
                if (permissionTree.IsMenu)
                {
                    model.PermissionType = RolePermissionType.Menu;
                    model.MenuId = permissionTree.Menu.Id;
                }
                else
                {
                    model.PermissionType = RolePermissionType.Button;
                    model.PermissionId = permissionTree.Permission.Id;
                }

                models.Add(model);

                if (item.Items != null && item.Items.Count() > 0)
                {
                    models.AddRange(GetSelectItems(item.Items));
                }
            }
            return models;
        }

        private Task OnTreeItemChecked(IEnumerable<TreeItem> items)
        {
            foreach(var item in items)
            {
                if (item.Checked)
                {
                    var temp_item = GetParentTreeItem(item, TreeItems);
                    if (temp_item != null)
                    {
                        temp_item.Checked = true;
                        StateHasChanged();
                    }
                }
            }

            
            return Task.CompletedTask;
        }

        /// <summary>
        /// 获取父节点
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private TreeItem GetParentTreeItem(TreeItem item, IEnumerable<TreeItem> treeItems)
        {
            foreach (var treeItem in treeItems)
            {
                if (treeItem.Items.Any(x => x.Key == item.Key))
                {
                    return treeItem;
                }
                else
                {
                    var temp_item = GetParentTreeItem(item, treeItem.Items);
                    if (temp_item != null)
                    {
                        return temp_item;
                    }
                }
            }
            return null;
        }

        private void SetTreeItems(IEnumerable<PermissionTreeModel> permissionTrees)
        {
            foreach (var permissionTree in permissionTrees)
            {
                TreeItem treeItem = new TreeItem();
                treeItem.Key = permissionTree;
                treeItem.Text = permissionTree.IsMenu ? permissionTree.Menu.Name : permissionTree.Permission.Name;
                TreeItems.Add(treeItem);
                RecursionTree(treeItem, permissionTree);
            }
        }
        /// <summary>
        /// 递归构建权限树
        /// </summary>
        /// <param name="menuTree"></param>
        /// <param name="menus"></param>
        private void RecursionTree(TreeItem treeItem, PermissionTreeModel permissionTree)
        {
            if (permissionTree.Childrens != null && permissionTree.Childrens.Count > 0)
            {
                List<TreeItem> treeItems = new List<TreeItem>();
                treeItem.Items = treeItems;
                foreach (var v_permissionTree in permissionTree.Childrens)
                {
                    TreeItem temp_treeItem = new TreeItem();
                    temp_treeItem.Key = v_permissionTree;
                    temp_treeItem.Text = v_permissionTree.IsMenu ? v_permissionTree.Menu.Name : v_permissionTree.Permission.Name;
                    treeItems.Add(temp_treeItem);
                    RecursionTree(temp_treeItem, v_permissionTree);
                }
            }
        }

    }
}
